package org.example.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.concurrent.TimeUnit;

public class NettyClient {
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(new NioEventLoopGroup());
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                socketChannel.pipeline()
                        .addLast(new LineBasedFrameDecoder(1024))
                        .addLast(new StringDecoder())
                        .addLast(new StringEncoder())
                        .addLast(new SimpleChannelInboundHandler<String>() {
                            @Override
                            protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
                                System.out.println(s);
                            }
                        });
            }
        });

        ChannelFuture connect = bootstrap.connect("localhost", 8080);
        connect.addListener(f -> {
            if(f.isSuccess()){
                System.out.println("客服端连接成功");

                EventLoop eventLoop = connect.channel().eventLoop();
                eventLoop.scheduleAtFixedRate(new Runnable() {
                    @Override
                    public void run() {
                        connect.channel().writeAndFlush("hello" + System.currentTimeMillis() + "\n");
                    }
                }, 0, 1, TimeUnit.SECONDS);
            }else{
                System.out.println("客户端连接失败");
            }
        });
    }
}
